/**************************************************
 * IdsTrust ECM RND                             ***
 * youngkeun, kim                               ***
 * wiseOne 2.0 new Mail Server                  ***
 * since 2008.10.                               ***
 *                                              ***
 * created at 2008. 10. 29.                           ***
 * created by ykkim                           ***
 **************************************************/
package com.idstrust.wiseone.sg.wisehr.common.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.mail.MessagingException;
import javax.mail.internet.MimeUtility;

/**
 * @author Administrator
 *
 */
public class DigetUtil {

	private DigetUtil() {}

	/**
	* Calculate digest of given String using given algorithm.
	* Encode digest in MIME-like base64.
	*
	* @param pass the String to be hashed
	* @param algorithm the algorithm to be used
	* @return String Base-64 encoding of digest
	*
	* @throws NoSuchAlgorithmException if the algorithm passed in cannot be found
	*/
	public static String digestString(String pass, String algorithm) throws NoSuchAlgorithmException {
		MessageDigest md;
		ByteArrayOutputStream bos;
		try {
			md = MessageDigest.getInstance(algorithm);
			byte[] digest = md.digest(pass.getBytes("iso-8859-1"));
			bos = new ByteArrayOutputStream();
			OutputStream encodedStream = MimeUtility.encode(bos, "base64");
			encodedStream.write(digest);
			return bos.toString("iso-8859-1");
		} catch (IOException ioe) {
			ioe.printStackTrace();
			throw new RuntimeException("Fatal error: " + ioe);
		} catch (MessagingException me) {
			me.printStackTrace();
			throw new RuntimeException("Fatal error: " + me);
		}
	}

	//nothing.
	public static String unDigestString(String pass, String algorithm) throws NoSuchAlgorithmException {

		ByteArrayInputStream bis;
		
		try {
			byte[] digest = pass.getBytes("iso-8859-1");
			bis = new ByteArrayInputStream(digest);
			MimeUtility.decode(bis, "base64");
		} catch (IOException ioe) {
			ioe.printStackTrace();
			throw new RuntimeException("Fatal error: " + ioe);
		} catch (MessagingException me) {
			me.printStackTrace();
			throw new RuntimeException("Fatal error: " + me);
		}
		return null;
	}

}
